import type { ModalMethods, ModalProps, UseModalReturnType } from '@/components/modal/src/types';
import { isProdMode } from '@/utils/env';
import { error } from '@/utils/log';

export function useModal(props: ModalProps): UseModalReturnType {
  const modalRef = ref<Nullable<ModalMethods>>(null);

  function getInstance() {
    const instance = unref(modalRef.value);
    if (!instance) {
      error('useModal: Modal instance is undefined!');
    }
    return instance;
  }

  function register(modalInstance: ModalMethods) {
    isProdMode() && tryOnUnmounted(() => {
      modalRef.value = null;
    });
    modalRef.value = modalInstance;

    watch(
      () => props,
      props => {
        props && modalInstance?.setProps(props);
      },
      {
        immediate: true,
        deep: true,
      },
    );
  }

  const methods: ModalMethods = {
    setProps: (props): void => {
      getInstance()?.setProps(props);
    },
    openModal() {
      getInstance()?.openModal();
    },
    closeModal() {
      getInstance()?.closeModal();
    },
    setLoading(loading) {
      getInstance()?.setLoading(loading);
    },
  };

  return [register, methods];
}
